package cn.hchaojie.ssm.web;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import cn.hchaojie.ssm.domain.Category;
import cn.hchaojie.ssm.domain.Post;
import cn.hchaojie.ssm.service.PostService;

/**
 * web层：请求参数封装、请求路径映射
 * spring mvc (model, view, controller)
 */
@Controller
public class PostController {
	@Autowired
	PostService service;

	// http://localhost/springmvc/pages/list.action
	@RequestMapping("/pages/list")
	public ModelAndView list(Model model) {
		// 查询所有文章列表
		List<Post> posts = service.findAll();
		
		// 跳转到文章列表对应的jsp页面，并且把文章列表显示出来
		ModelAndView mv = new ModelAndView();	// 跳到哪个页面（view），页面上需要显示什么数据（model）
		mv.setViewName("posts");
		// mv.addObject("posts", posts);		// posts对象会传给jsp页面
		model.addAttribute("posts", posts);
		
		return mv;
	}
	
	@RequestMapping("/pages/list_json")
	@ResponseBody
	public List<Post> listJson() {
		// 查询所有文章列表
		List<Post> posts = findPosts();
		
		return posts;
	}
	
	@RequestMapping("/pages/post_by_id")
	@ResponseBody	// 对返回数据进行序列化
	public Post findById(int id) {
		Post p = new Post();
		p.setId(id);
		p.setTitle("java");
		p.setCreated(new Date());
		
		Category c = new Category();
		c.setId(2);
		c.setName("spring");
		
		p.setCategory(c);
		
		return p;
	}
	
	private List<Post> findPosts() {
		List<Post> posts = new ArrayList<>();
		
		for (int i = 0; i < 10; i++) {
			Post p = new Post();
			p.setId(i + 1);
			p.setTitle("java spring mvc" + i);
			p.setCreated(new Date());
			
			posts.add(p);
		}
		
		return posts;
	}
	
	@RequestMapping("/post/edit_form")
	public String eidtForm(Model model) {
		model.addAttribute("id", 1);
		
		return "post_form";
	}
	
	@RequestMapping("/post/edit")
	public String edit(Post p) {
		System.out.println("post:" + p);
		System.out.println(p.getCategory());
		return "success";
	}
}
